# ITBuy.controllers Module
#
# @abstract Description
#
angular
    .module('Ajani.controllers', [])
    .controller('AppController', ['$scope', '$rootScope', '$routeParams', '$http', '$location', '$window', 'Ping', ($scope, $rootScope, $routeParams, $http, $location, $window, Ping) ->
        $scope.cUser = loggedin: false, display: "", admin: false
        $scope.navi = 
            home: false
            shops: false
            user: false
            signin: false
            user_profile: false
            user_admin: false
            first: true
            second: true
        $scope.currentUrl = ""
        $scope.pageState = isLoadingRes: false
        $scope.itemDetails = 
            item: {}
            user: {}
        $scope.msgItm = {}
        $scope.msgViw = {}
        $scope.msgNew = to: {}
        $scope.ping = 
            msg: true

        $scope.$on 'editor:content', (event, val) ->
            $scope.msgItm.content = val

        $scope.topbar = () ->
            angular.element(document).foundationTopBar()

        checkUser = (login) ->
            if login
                url = '/_/users/me?q=detail&u=' + $location.absUrl()
            else
                url = '/_/users/me'
            $http
                .get(url)
                .success (data, status, headers, config) ->
                    if data.status == "error"
                        if data.message == "Login Required"
                            $window.location.href = data.url
                        else
                            $scope.cUser = loggedin: false, display: "", admin: false
                    else
                        if data.message == "uninitialized"
                            $scope.$broadcast 'app:inituser'
                        if $location.path().indexOf('/signin') >= 0 and data.message == "success"
                            $scope.$broadcast 'app:usersignedin'
                        $scope.cUser = loggedin: true, display: data['display'], admin: data['admin'], img: data['img']
                        $scope.navi.user = $location.path() == "/user/"+$scope.cUser.display or $location.path() == "/admin"
                        $scope.navi.user_profile = $location.path() == "/user/"+$scope.cUser.display
                        $scope.navi.user_admin = $location.path() == "/admin"
                    # console.log data
                .error (data, status, headers, config) ->
                    $scope.cUser = loggedin: false, display: "", admin: false

        $scope.$on '$routeChangeStart', ($next, $current) ->
            $scope.pageState.isLoadingRes = true

        $scope.$on '$routeChangeSuccess', ($currentRoute, $previousRoute) ->
            $scope.pageState.isLoadingRes = false
            path = $location.path()
            if path.indexOf('/user') >= 0
                $scope.currentUrl = "/"
            else
                $scope.currentUrl = $location.url()
            $scope.navi.home = path == "/"
            $scope.navi.shops = path.indexOf("/shops") >= 0

            if path.indexOf("/signin") >= 0 and $routeParams.f == undefined and $routeParams.from != undefined
                $scope.navi.signin = true
                checkUser(true)
            else
                $scope.navi.signin = false
                checkUser(false)

        $scope.$on '$routeChangeError', ($event, $current, $previous, $rejection) ->
            if not $previous
                $location.url('/')
                $location.replace()

            if $rejection == "Login Required"
                $('#loginRequiredModal').reveal()

        if $scope.cUser.loggedin
            Ping.msg (result) ->
                $scope.ping.msg = result.data

    ])
    .controller('HomeController', ['$scope', 'ItemsHome', ($scope, ItemsHome) ->
        # items = ItemsHome
        $scope.home = ItemsHome
        # $scope.home.new = ItemsHome.newest
        # $scope.home.pops = ItemsHome.pops
    ])
    .controller('ShopsController', ['$scope', '$http', '$routeParams', 'ItemsShop', ($scope, $http, $routeParams, ItemsShop) ->
        $scope.opt = {}
        if $routeParams.cat
            if $routeParams.cat == "books"
                $scope.snav = 
                    all: false
                    books: true
                    elec: false
                    serv: false
                $scope.opt.brd = ["BOOKS", "ALL"]
            else if $routeParams.cat == "electronics"
                $scope.snav = 
                    all: false
                    books: false
                    elec: true
                    serv: false
                $scope.opt.brd = ["ELECTRONICS", "ALL"]
            else if $routeParams.cat == "services"
                $scope.snav = 
                    all: false
                    books: false
                    elec: false
                    serv: true
                $scope.opt.brd = ["SERVICES", "ALL"]
        else
            $scope.snav = 
                all: true
                books: false
                elec: false
                serv: false
            $scope.opt.brd = ["ALL"]
        $scope.shops = ItemsShop
    ])
    .controller('UserRegisterController', ['$scope', '$http', ($scope, $http) ->
        $scope.success = false
        $scope.httpError = false
        $scope.user = {}

        $scope.submit = () ->
            $http
                .post('/_/users/register', $scope.user)
                .success (data, status, headers, config) ->
                    $scope.success = true
                    # console.log data
                .error (data, status, headers, config) ->
                    $scope.httpError = true
                    # console.log status
    ])
    .controller('UserSigninController', ['$scope', '$http', '$location', '$routeParams', '$timeout', ($scope, $http, $location, $routeParams, $timeout) ->

        check = () ->
            if not $routeParams.f and not $routeParams.from
                $location.url('/')
                $location.replace()
            if $routeParams.f is "1" and $routeParams.from
                $('#welcomeFirstModal').reveal {
                    closeOnBackgroundClick: false
                    closed: () ->
                        $scope.$apply () ->
                            $location.url($routeParams.from)
                            $location.replace()
                }
            #     $location.url($routeParams.from)
            # $location.replace()
        check()

        $scope.$on "app:usersignedin", (event) ->
            $timeout () ->
                $('#welcomeFirstModal').trigger('reveal:close')
            ,1000

        $scope.$on "app:inituser", (event) ->
            $http
                .post('/_/users/me')
                .success (data, status, headers, config) ->
                    if data.status == "success"
                        $timeout () ->
                            $('#welcomeFirstModal').trigger('reveal:close')
                        ,1000
    ])
    .controller('UserSignoutController', ['$scope', '$http', '$location', '$routeParams', '$window', ($scope, $http, $location, $routeParams, $window) ->
        from = if $routeParams.from then $routeParams.from else '/'
        $http
            .get('/_/users/signout?u=' + from)
            .success (data, status, headers, config) ->
                if data.status is "success"
                    $window.location.href = data.url
                else if data.status is "error"
                    $location.url '/'
                    $location.replace()
    ])
    .controller('UserAreaController', ['$scope', '$routeParams', '$timeout', 'UserProfile', 'UserResource', ($scope, $routeParams, $timeout, UserProfile, UserResource) ->
        $scope.opt = {}
        $scope.pUserC = 
            user:
                img: ""
        $scope.loaded = () ->
            $scope.opt.loaded = true
        if $routeParams.res
            if $routeParams.res == "validations"
                $scope.snav = 
                    acc: true, prof: false, vald: true, sec: false
                    conn: false, frn: false, soc: false
                    pm: false, inb: false, outb: false
                    coll: false, wsh: false, sel: false
                $scope.pcontent = "/partials/user/validation.html"
                $scope.opt.brd = ["Account Settings", "Validations"]

            else if $routeParams.res == "security-privacy"
                $scope.snav = 
                    acc: true, prof: false, vald: false, sec: true
                    conn: false, frn: false, soc: false
                    pm: false, inb: false, outb: false
                    coll: false, wsh: false, sel: false
                $scope.pcontent = "/partials/user/security.html"
                $scope.opt.brd = ["Account Settings", "Security and Privacy"]

            else if $routeParams.res == "friends"
                $scope.snav = 
                    acc: false, prof: false, vald: false, sec: false
                    conn: true, frn: true, soc: false
                    pm: false, inb: false, outb: false
                    coll: false, wsh: false, sel: false
                $scope.pcontent = "/partials/user/friends.html"
                $scope.opt.brd = ["Connections", "Friends"]

            else if $routeParams.res == "social-accounts"
                $scope.snav = 
                    acc: false, prof: false, vald: false, sec: false
                    conn: true, frn: false, soc: true
                    pm: false, inb: false, outb: false
                    coll: false, wsh: false, sel: false
                $scope.pcontent = "/partials/user/social.html"
                $scope.opt.brd = ["Connections", "Social Accounts"]

            else if $routeParams.res == "inbox"
                $scope.snav = 
                    acc: false, prof: false, vald: false, sec: false
                    conn: false, frn: false, soc: false
                    pm: true, inb: true, outb: false
                    coll: false, wsh: false, sel: false
                $scope.pm = UserResource
                $scope.readit = (id) ->
                    $scope.pm.msgs[id].read = true
                    $scope.pm.$read({i: $scope.pm.msgs[id].id})
                $scope.pcontent = "/partials/user/inbox.html?"+Date.now()
                $scope.opt.brd = ["Private Messages", "Inbox"]

            else if $routeParams.res == "outbox"
                $scope.snav = 
                    acc: false, prof: false, vald: false, sec: false
                    conn: false, frn: false, soc: false
                    pm: true, inb: false, outb: true
                    coll: false, wsh: false, sel: false
                $scope.pm = UserResource
                $scope.pcontent = "/partials/user/outbox.html?"+Date.now()
                $scope.opt.brd = ["Private Messages", "Outbox"]

            else if $routeParams.res == "wishlist"
                $scope.snav = 
                    acc: false, prof: false, vald: false, sec: false
                    conn: false, frn: false, soc: false
                    pm: false, inb: false, outb: false
                    coll: true, wsh: true, sel: false
                $scope.pcontent = "/partials/user/wishlist.html"
                $scope.opt.brd = ["Items Collections", "Wishlist"]

            else if $routeParams.res == "for-sell"
                $scope.snav = 
                    acc: false, prof: false, vald: false, sec: false
                    conn: false, frn: false, soc: false
                    pm: false, inb: false, outb: false
                    coll: true, wsh: false, sel: true
                $scope.pcontent = "/partials/user/sell.html"
                $scope.opt.brd = ["Items Collections", "For Sell"]

            else
                $location.path('/user/'+$scope.cUser.display)
                $location.replace()

        else
            $scope.snav = 
                acc: true, prof: true, vald: false, sec: false
                conn: false, frn: false, soc: false
                pm: false, inb: false, outb: false
                coll: false, wsh: false, sel: false
            $scope.pcontent = "/partials/user/profile.html"
            $scope.opt.brd = ["Account Settings", "Profile"]
            # $scope.pUser = User.me({q: "detail"})

            $scope.pUser = UserProfile
    ])
    .controller('AdminAreaController', ['$scope', '$routeParams', '$timeout', 'Admin', 'UserProfile', 'AdminRes', ($scope, $routeParams, $timeout, Admin, UserProfile, AdminRes) ->
        $scope.opt = {}
        $scope.pUserC = 
            user:
                img: ""
        $scope.loaded = () ->
            $scope.opt.loaded = true
        if $routeParams.pat and not $routeParams.sub
            if $routeParams.pat == "resources"
                $location.path('/admin')
                $location.replace()
            else if $routeParams.pat == "logs"
                $scope.snav = 
                    das: false
                    res: false, usr: false, itm: false
                    log: true
                    sett: false
                $scope.pcontent = "/partials/admin/logs.html"
                $scope.opt.brd = ["Admin", "Application Logs"]
            else if $routeParams.pat == "settings"
                $scope.snav = 
                    das: false
                    res: false, usr: false, itm: false
                    log: false
                    sett: true
                $scope.pcontent = "/partials/admin/settings.html"
                $scope.opt.brd = ["Admin", "Application Settings"]
        else if $routeParams.pat and $routeParams.sub
            if $routeParams.pat == "resources" and $routeParams.sub == "users"
                $scope.snav = 
                    das: false
                    res: true, usr: true, itm: false
                    log: false
                    sett: false

                $scope.lUser = AdminRes

                $scope.pcontent = "/partials/admin/userlist.html?"+Date.now()
                $scope.opt.brd = ["Admin", "Resources", "Users List"]
            else if $routeParams.pat == "resources" and $routeParams.sub == "items"
                $scope.snav = 
                    das: false
                    res: true, usr: false, itm: true
                    log: false
                    sett: false

                $scope.lItem = AdminRes

                $scope.pcontent = "/partials/admin/itemlist.html"
                $scope.opt.brd = ["Admin", "Resources", "Items List"]
        else
            $scope.snav = 
                das: true
                res: false, usr: false, itm: false
                log: false
                sett: false

            $scope.loading = [true, true]
            $scope.lUser = Admin.users({ct:'1'}, () ->
                $scope.loading[0] = false
            )

            $scope.loading = [true, true]
            $scope.lItem = Admin.items({ct:'1'}, () ->
                $scope.loading[1] = false
            )
            $scope.pcontent = "/partials/admin/dashboard.html?"+Date.now()
            $scope.opt.brd = ["Admin", "Dashboard"]
            $scope.pUser = UserProfile
        $scope.next = (kind) ->
            if kind is "user"
                $scope.loading[0] = true
                $scope.lUser = Admin.users({p:'next', c: $scope.lUser.next_cursor}, () ->
                    $scope.loading[0] = false
                )
            else if kind is "item"
                $scope.loading[1] = true
                $scope.lItem = Admin.items({p:'next', c: $scope.lItem.next_cursor}, () ->
                    $scope.loading[1] = false
                )
            else
                false

        $scope.prev = (kind) ->
            if kind is "user"
                $scope.loading[0] = true
                $scope.lUser = Admin.users({p:'prev', c: $scope.lUser.prev_cursor}, () ->
                    $scope.loading[0] = false
                )
            else if kind is "item"
                $scope.loading[1] = true
                $scope.lItem = Admin.items({p:'prev', c: $scope.lItem.prev_cursor}, () ->
                    $scope.loading[1] = false
                )
            else
                false
    ])
    .controller('ItemNewController', ['$scope', '$http', '$location', 'UserProfile', ($scope, $http, $location, UserProfile) ->
        $scope.success = false
        $scope.httpError = false
        $scope.opt = 
            th: []
            id: []
            prog:[]
        $scope.item = 
            imgadded: false
            data:
                act: true
                imgs: []
                private: false
                # desc: ''

        $scope.$on 'editor:desc', (event, val) ->
            $scope.item.data.desc = val

        $scope.submit = () ->
            console.log $scope.item.data
            for imgs in $scope.item.data.imgs
                delete imgs.files
                delete imgs.$$hashkey

            $http
                .post('/_/items/new', $scope.item.data)
                .success (data, status, headers, config) ->
                    if data.status == "success"
                        $location.path('/')
                        $location.replace()
    ])
